package cn.zhoujing.demo.redis.config;

import cn.zhoujing.demo.redis.enums.AuthorizedGrantTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @author zhoujing
 * @createTime 2023/11/19 - 17:11
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Qualifier("tokenConverter")
    @Autowired
    private JwtAccessTokenConverter accessTokenConverter;


    /**
     * 用来配置令牌端点的安全约束
     *
     * /oauth/authorize：授权端点。
     * /oauth/token：令牌端点。
     * /oauth/confirm_access：用户确认授权提交端点。
     * /oauth/error：授权服务错误信息端点。
     * /oauth/check_token：用于资源服务访问的令牌解析端点。
     * /oauth/token_key：提供公有密匙的端点，如果你使用JWT令牌的话。
     *
     * @param authorizationServerSecurityConfigurer
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer authorizationServerSecurityConfigurer) throws Exception {
        authorizationServerSecurityConfigurer
                //配置哪些接口可以被访问
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                // 允许表单认证
                .allowFormAuthenticationForClients();
    }

    /**
     * 用来配置客户端详情服务（ClientDetailsService），
     * 客户端详情信息在 这里进行初始化，
     * 你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息。
     * <p>
     * withClient：客户端（如：管理后台（admin）、用户端）
     * secret：客户端密码
     * resourceIds：客户端id
     * authorizedGrantTypes：这个客户端可以得到token的几种方式
     * scopes：范围，上面的配置是这个客户端的范围
     *
     * @param clientDetailsServiceConfigurer
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clientDetailsServiceConfigurer) throws Exception {
        clientDetailsServiceConfigurer
                // inMemory 存储在缓存中，jdbc 存储到数据库中
                .inMemory()
                // 设置客户端（平台）的id和密码
                .withClient("client1")
                .secret(passwordEncoder.encode("123456"))
                // 给client一个id,这个在client的配置里要用的, 能使用的资源id
                .resourceIds("resource1")
                //允许的申请token的方式
                .authorizedGrantTypes(
                        AuthorizedGrantTypeEnum.AUTHORIZATION_CODE.getTypeName(),
                        AuthorizedGrantTypeEnum.PASSWORD.getTypeName(),
                        AuthorizedGrantTypeEnum.IMPLICIT.getTypeName(),
                        AuthorizedGrantTypeEnum.REFRESH_TOKEN.getTypeName(),
                        AuthorizedGrantTypeEnum.CLIENT_CREDENTIALS.getTypeName())
                // 授权的范围,每个resource会设置自己的范围.
                .scopes("scope1")
                .autoApprove(false)
                .redirectUris("http://www.baidu.com")
                // 设置当前客户端accessToken和refreshToken的有效期
                .accessTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(6))
                .refreshTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1));

//                 配置更多客户端
//                .and()
//                .withClient("client2")
//                ..secret(passwordEncoder.encode("123456"))
//                .resourceIds("resource2")
//                ……

    }


    @Autowired
    private AuthenticationManager authenticationManager;

    /**
     * 授权码模式存取
     *
     * @return
     */
    @Bean
    public AuthorizationCodeServices authorizationCodeServices() {
        return new InMemoryAuthorizationCodeServices();
    }


    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;


    /**
     * 用来配置令牌（token）的访问端点和令牌服务(token services)。
     *
     * @param authorizationServerEndpointsConfigurer
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer authorizationServerEndpointsConfigurer) throws Exception {
        authorizationServerEndpointsConfigurer
                // 认证管理器
                .authenticationManager(authenticationManager)
                // 授权码管理
                .authorizationCodeServices(authorizationCodeServices)
                // Token管理
                .tokenServices(tokenServices())
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }


    /**
     * token管理服务
     *
     * @return
     */
    @Bean
    public AuthorizationServerTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        // 客户端信息服务 cn/zhoujing/demo/oauth/adapter/AuthorizationServerConfigurerAdapter.java:50
        defaultTokenServices.setClientDetailsService(clientDetailsService);
        // 是否刷新令牌
        defaultTokenServices.setSupportRefreshToken(true);
        // 令牌存储策略
        defaultTokenServices.setTokenStore(tokenStore);
        // 令牌初始有效期（秒）
        defaultTokenServices.setAccessTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(12));
        // 令牌续后的有效期（秒）
        defaultTokenServices.setRefreshTokenValiditySeconds((int) TimeUnit.HOURS.toSeconds(24));

        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        defaultTokenServices.setTokenEnhancer(tokenEnhancerChain);
        
        return defaultTokenServices;
    }

}
